<?php

namespace addons\kzvote\model;

use app\common\library\Auth;
use app\common\model\kzvote\Openid;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\Model;

class UserModel extends User
{
    // 表名
    protected $name = 'user';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    /**
     * 快速注册用户
     * @param string $username
     * @param string $nickname
     * @param int    $gender
     * @return UserModel
     */
    public static function fastRegister($oauth,string $platform)
    {
        return Db::transaction(function () use ($oauth,$platform){
            $salt = Random::alnum();
            $user = self::create([
                'email'     => rand(100000,999999) . '@qq.com',
                'salt'      => $salt,
                'nickname'  => '投票用户_',
                'status'    => 'normal',
                'logintime' => time(),
            ]);
            $user->nickname .= $user->id;
            $user->save();
            Openid::create([
                'user_id' => $user->id,
                'platform' => $platform,
                'openid' => $platform == 'wxapp' ? $oauth['openid'] : '',
                'open_id' => $platform == 'wechat' ? $oauth['openid'] : '',
                'unionid' => isset($oauth['unionid']) ? $oauth['unionid'] : '',
            ]);
            return $user;
        });

    }

    /**
     * 根据微信接口返回信息，实现用户登录
     * @param $user_id
     * @return Model
     */
    public static function oauth($arr)
    {
        $where = [];
        if (isset($arr['unionid'])){
            $where = ['unionid'=>$arr['unionid']];
        }else{
            $where = ['open_id | openid'=>$arr['openid']];
        }
        $openid = Openid::get($where);
        return $openid;
    }

    /**
     * 根据第三方登录信息，实现用户登录
     * @param $user_id
     * @return Model
     */
    public static function thirdOauth($arr)
    {
        $where = [];
        if (isset($arr['unionid'])){
            $where['unionid'] = $arr['unionid'];
        }
        $where['openid'] = $arr['openid'];
        $openid = \addons\third\model\Third::get($where);
        return $openid;
    }


}
